$(document).ready(function() {
    const token = localStorage.getItem(STORAGE_KEYS.TOKEN);
    const userInfo = JSON.parse(localStorage.getItem(STORAGE_KEYS.USER_INFO) || '{}');
    
    if (token && userInfo.id && userInfo.role) {
        window.location.href = ROLE_PAGES[userInfo.role];
        return;
    }
    
    $('#loginForm').on('submit', function(e) {
        e.preventDefault();
        
        const userId = $('#userId').val();
        const password = $('#password').val();
        const role = $('input[name="role"]:checked').val();
        const $loginMessage = $('#loginMessage');
        
        if (!userId || !password) {
            utils.showMessage($loginMessage, '请输入用户ID和密码');
            return;
        }
        
        $.ajax({
            url: `${API_BASE_URL}/auth/login`,
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                user_id: userId,
                password: password,
                role: parseInt(role)
            }),
            success: function(response) {
                const result = utils.handleApiResponse(response);
                
                if (result.success && result.data) {
                    const data = result.data;
                    
                    localStorage.setItem(STORAGE_KEYS.TOKEN, data.access_token);
                    localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify({
                        id: userId,
                        name: data.user_info.name,
                        role: data.user_info.role,
                        major: data.user_info.major || '',
                        title: data.user_info.title || ''
                    }));
                    
                    utils.showMessage($loginMessage, '登录成功，正在跳转...', 'success');
                    
                    setTimeout(function() {
                        window.location.href = ROLE_PAGES[data.user_info.role];
                    }, 1000);
                } else {
                    utils.showMessage($loginMessage, result.message || '登录失败');
                }
            },
            error: function(xhr) {
                const errorMessage = utils.handleApiError(xhr, '登录失败，请检查用户名和密码');
                utils.showMessage($loginMessage, errorMessage);
            }
        });
    });
}); 